package com.ruoyi.project.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.es.SysDeptRepository;
import com.ruoyi.project.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataScope;
import com.ruoyi.framework.web.domain.TreeSelect;
import com.ruoyi.project.system.service.ISysDeptService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 部门管理 服务实现
 * 
 * @author ruoyi
 */
@Service
public class SysDeptServiceImpl  implements ISysDeptService
{
    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysDeptImgMapper deptImgMapper;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private SysCategoryMapper sysCategoryMapper;

    @Autowired
    private SysAttrMapper sysAttrMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    /**
     * 查询部门管理数据
     * 
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept)
    {
        return deptMapper.selectDeptList(dept);
    }

    /**
     * 构建前端所需要树结构
     * 
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts)
    {
        List<Long> deptIds=new ArrayList<>();
        for(SysDept sysDept:depts){
            deptIds.add(sysDept.getDeptId());
        }

        List<Long> parentIds=new ArrayList<>();
        for(SysDept sysDept:depts){
            if(!deptIds.contains(sysDept.getParentId())){
                parentIds.add(sysDept.getDeptId());
            }
        }
        List<SysDept> returnList = new ArrayList<SysDept>();
        for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext();)
        {
            SysDept t = (SysDept) iterator.next();
            // 根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (parentIds.contains(t.getDeptId()))
            {
                recursionFn(depts, t);
                returnList.add(t);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     * 
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Integer> selectDeptListByRoleId(Long roleId)
    {
        return deptMapper.selectDeptListByRoleId(roleId);
    }

    /**
     * 店铺分类
     * @return
     */
    @Override
    public List<SysCategory> selectCategory() {
        List<SysCategory> result=new ArrayList<>();
        List<SysCategory> list=sysCategoryMapper.selectCategoryAll();
        if(!list.isEmpty()){
            for(SysCategory sysCategory:list){
                if(null==sysCategory.getParentId()){
                    result.add(sysCategory);
                }
            }
        }
        if(!result.isEmpty()){
            for(SysCategory sysCategory:result){
                List<SysCategory> subCategory=new ArrayList<>();
                for(SysCategory category:list){
                    if(sysCategory.getCategoryId().equals(category.getParentId())){
                        subCategory.add(category);
                    }
                }
                sysCategory.setSubCategories(subCategory);
            }
        }
        return result;
    }

    /**
     * 根据部门ID查询信息
     * 
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId)
    {
        SysDept sysDept=deptMapper.selectDeptById(deptId);
        if(null!=sysDept){
            List<SysDeptImg> sysDeptImgList=new ArrayList<>();
            sysDeptImgList=deptImgMapper.selectDeptImgByDeptId(deptId);
            if(!sysDeptImgList.isEmpty()){
                for(SysDeptImg img:sysDeptImgList){
                    img.setUrl(serverConfig.getUrl()+img.getUrl());
                }
            }
            sysDept.setFileList(sysDeptImgList);
        }
        return sysDept;
    }

    /**
     * 是否存在子节点
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId)
    {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0 ? true : false;
    }

    /**
     * 查询部门是否存在用户
     * 
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId)
    {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0 ? true : false;
    }

    /**
     * 校验部门名称是否唯一
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept)
    {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存部门信息
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDept(SysDept dept)
    {
        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new CustomException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        int flag=deptMapper.insertDept(dept);
        if(flag>0){
            insertDeptAttr(dept);
            insertDeptCategory(dept);
            if(null!=dept.getFileList()&&dept.getFileList().size()>0){
                for(SysDeptImg sysDeptImg:dept.getFileList()){
                    sysDeptImg.setDeptId(dept.getDeptId());
                    sysDeptImg.setUrl(sysDeptImg.getUrl().replace(serverConfig.getUrl(),""));
                    int rows=deptImgMapper.insertDeptImg(sysDeptImg);
                    if(rows<0){
                        throw new CustomException("系统错误");
                    }
                }
            }
        }
        AsyncManager.me().execute(AsyncFactory.indexSysDept(dept.getDeptId()));
        return flag;
    }


    public void insertDeptAttr(SysDept dept)
    {
        Long[] attrIds = dept.getAttrIds();
        if (StringUtils.isNotNull(attrIds))
        {
            // 新增用户与岗位管理
            List<SysDeptAttr> list = new ArrayList<SysDeptAttr>();
            for (Long attrId : attrIds)
            {
                SysDeptAttr up = new SysDeptAttr();
                up.setDeptId(dept.getDeptId());
                up.setAttrId(attrId);
                list.add(up);
            }
            if (list.size() > 0)
            {
                sysAttrMapper.batchDeptAttr(list);
            }
        }
    }

    public void insertDeptCategory(SysDept dept)
    {
        Long[] categoryIds = dept.getCategoryIds();
        if (StringUtils.isNotNull(categoryIds))
        {
            List<SysDeptCategory> list = new ArrayList<SysDeptCategory>();
            for (Long categoryId : categoryIds)
            {
                SysDeptCategory up = new SysDeptCategory();
                up.setDeptId(dept.getDeptId());
                up.setCategoryId(categoryId);
                list.add(up);
            }
            if (list.size() > 0)
            {
                sysCategoryMapper.batchDeptCategory(list);
            }
        }
    }


    /**
     * 修改保存部门信息
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDept(SysDept dept)
    {
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateDept(dept);
        if(result>0){

            // 删除部门与属性关联
            sysAttrMapper.deleteDeptAttrByDeptId(dept.getDeptId());
            // 新增部门与属性关联
            insertDeptAttr(dept);
            // 删除部门与分类关联
            sysCategoryMapper.deleteDeptCategoryByDeptId(dept.getDeptId());
            // 新增部门与分类关联
            insertDeptCategory(dept);
            deptImgMapper.deleteByDeptId(dept.getDeptId());
            if(null!=dept.getFileList()&&dept.getFileList().size()>0){
                for(SysDeptImg sysDeptImg:dept.getFileList()){
                    sysDeptImg.setDeptId(dept.getDeptId());
                    sysDeptImg.setUrl(sysDeptImg.getUrl().replace(serverConfig.getUrl(),""));
                    int rows=deptImgMapper.insertDeptImg(sysDeptImg);
                    if(rows<0){
                        throw new CustomException("系统错误");
                    }
                }
            }
        }
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(dept);
        }
        AsyncManager.me().execute(AsyncFactory.indexSysDept(dept.getDeptId()));
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     * 
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDept dept)
    {
        String updateBy = dept.getUpdateBy();
        dept = deptMapper.selectDeptById(dept.getDeptId());
        dept.setUpdateBy(updateBy);
        deptMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     * 
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId)
    {
        return deptMapper.deleteDeptById(deptId);
    }

    @Override
    public SysDept selectDeptDetailById(Long deptId) {
        SysDept sysDept=deptMapper.selectDeptById(deptId);
        if(null!=sysDept){
            /**
             * 商家图片
             */
            List<SysDeptImg> sysDeptImgList=new ArrayList<>();
            sysDeptImgList=deptImgMapper.selectDeptImgByDeptId(deptId);
            /*if(!sysDeptImgList.isEmpty()){
                for(SysDeptImg img:sysDeptImgList){
                    img.setUrl(serverConfig.getUrl()+img.getUrl());
                }
            }*/
            sysDept.setFileList(sysDeptImgList);
            /**
             * 商家配送方式
             */
            sysDept.setDeliveryStr(sysDictDataMapper.selectDictLabel("sys_delivery_mode",sysDept.getDelivery()));
            /**
             * 商家属性
             */
            sysDept.setAttrData(sysAttrMapper.selectListByDeptId(sysDept.getDeptId()));
            /**
             * 商家分类
             */
            sysDept.setCategoryData(sysCategoryMapper.selectListByDeptId(sysDept.getDeptId()));
        }
        return sysDept;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                // 判断是否有子节点
                Iterator<SysDept> it = childList.iterator();
                while (it.hasNext())
                {
                    SysDept n = (SysDept) it.next();
                    recursionFn(list, n);
                }
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
            if (n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
